package com.vipheyue.campusrecyce.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.vipheyue.campusrecyce.R;
import com.vipheyue.campusrecyce.adapter.RecyclerAdapter;
import com.vipheyue.campusrecyce.bean.MyUser;
import com.vipheyue.campusrecyce.bean.ThingBean;
import com.vipheyue.campusrecyce.utils.CheckTextUtil;
import com.vipheyue.campusrecyce.utils.GlideLoader;
import com.yancy.imageselector.ImageConfig;
import com.yancy.imageselector.ImageSelector;
import com.yancy.imageselector.ImageSelectorActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadBatchListener;

public class ReleaseActivity extends AppCompatActivity {


    @Bind(R.id.iv_Menu_leftImg)
    ImageView iv_Menu_leftImg;
    @Bind(R.id.tv_Menu_leftTitle)
    TextView tv_Menu_leftTitle;
    @Bind(R.id.rl_menu_left)
    RelativeLayout rl_menu_left;
    @Bind(R.id.tv_Menu_Title)
    TextView tv_Menu_Title;
    @Bind(R.id.iv_menu_rightTitle)
    TextView iv_menu_rightTitle;
    @Bind(R.id.iv_menu_right)
    ImageView iv_menu_right;
    @Bind(R.id.rl_menu_right)
    RelativeLayout rl_menu_right;
    @Bind(R.id.btn_getImage)
    Button btn_getImage;
    @Bind(R.id.recycler)
    RecyclerView recycler;
    @Bind(R.id.et_release_name)
    EditText et_release_name;
    @Bind(R.id.et_release_price)
    EditText et_release_price;
    @Bind(R.id.et_release_phone)
    EditText et_release_phone;
    @Bind(R.id.et_release_detail)
    EditText et_release_detail;
    @Bind(R.id.btn_release_commit)
    Button btn_release_commit;
    @Bind(R.id.tvOptions)
    TextView tvOptions;
    private RecyclerAdapter adapter;

    private ArrayList<String> imgPathList = new ArrayList<>();
    private SVProgressHUD mSVProgressHUD;

    private ArrayList<String> options1Items = new ArrayList<String>();
    OptionsPickerView pvOptions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release);
        ButterKnife.bind(this);
        tv_Menu_Title.setText("发布");
        initView();
    }

    private void initView() {
        mSVProgressHUD = new SVProgressHUD(this);
        RecyclerView recycler = (RecyclerView) super.findViewById(R.id.recycler);

        btn_getImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ImageConfig imageConfig
                        = new ImageConfig.Builder(
                        // GlideLoader 可用自己用的缓存库
                        new GlideLoader())
                        // 如果在 4.4 以上，则修改状态栏颜色 （默认黑色）
                        .steepToolBarColor(getResources().getColor(R.color.blue))
                        // 标题的背景颜色 （默认黑色）
                        .titleBgColor(getResources().getColor(R.color.blue))
                        // 提交按钮字体的颜色  （默认白色）
                        .titleSubmitTextColor(getResources().getColor(R.color.white))
                        // 标题颜色 （默认白色）
                        .titleTextColor(getResources().getColor(R.color.white))
                        // 开启多选   （默认为多选）  (单选 为 singleSelect)
//                        .singleSelect()
                        .crop()
                        // 多选时的最大数量   （默认 9 张）
                        .mutiSelectMaxSize(3)
                        // 已选择的图片路径
                        .pathList(imgPathList)
                        // 拍照后存放的图片路径（默认 /temp/picture）
                        .filePath("/ImageSelector/Pictures")
                        // 开启拍照功能 （默认开启）
                        .showCamera()
                        .build();


                ImageSelector.open(ReleaseActivity.this, imageConfig);   // 开启图片选择器

            }
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        recycler.setLayoutManager(layoutManager);
        adapter = new RecyclerAdapter(this, imgPathList);
        recycler.setAdapter(adapter);
    }


    @OnClick({R.id.rl_menu_left, R.id.btn_release_commit,R.id.tvOptions})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_menu_left:
                finish();
                break;
            case R.id.btn_release_commit:

                if (CheckTextUtil.textIsEmpty(et_release_name) || CheckTextUtil.textIsEmpty(et_release_price) || CheckTextUtil.textIsEmpty(et_release_phone) || CheckTextUtil.textIsEmpty(et_release_detail)||CheckTextUtil.textIsEmpty(tvOptions) ) {
                    Toast.makeText(this, "请填写各项数据", Toast.LENGTH_SHORT).show();
                    return;
                }
                btn_release_commit.setEnabled(false);
                ThingBean thingBean = new ThingBean();
                MyUser user = BmobUser.getCurrentUser(this, MyUser.class);
                thingBean.setReleaseUser(user);
                thingBean.setShow(true);
                thingBean.setName(et_release_name.getText().toString().trim());
                thingBean.setPrice(et_release_price.getText().toString().trim());
                thingBean.setPhone(et_release_phone.getText().toString().trim());
                thingBean.setLocation(user.getSchool());
                thingBean.setDetail(et_release_detail.getText().toString().trim());
                thingBean.setCategory(tvOptions.getText().toString());
                //添加图片
                mSVProgressHUD.show();
                if (imgPathList.size() > 0) {
                    //TODO 上传图片
                    upload(thingBean);
                    return;
                }
                saveToNet(thingBean);
                break;
            case R.id.tvOptions:
                choseType();
                break;

        }
    }

    private void saveToNet(ThingBean thingBean) {
        thingBean.save(this, new SaveListener() {
            @Override
            public void onSuccess() {
                Toast.makeText(ReleaseActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                finish();
            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(ReleaseActivity.this, "提交失败", Toast.LENGTH_SHORT).show();
                if (mSVProgressHUD.isShowing()) {
                    mSVProgressHUD.dismiss();
                }
                btn_release_commit.setEnabled(true);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ImageSelector.IMAGE_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);

            for (String path : pathList) {
                Log.i("ImagePathList", path);
                File file = new File(path);
                Log.i(".......", file.length() + "");
            }

            this.imgPathList.clear();
            this.imgPathList.addAll(pathList);
            adapter.notifyDataSetChanged();


        }
    }

    /***
     * 批量上传文件
     *
     * @param thingBean
     */
    //详细示例可查看BmobExample工程中BmobFileActivity类
    public void upload(final ThingBean thingBean) {

        BmobFile.uploadBatch(ReleaseActivity.this, (String[]) imgPathList.toArray(new String[imgPathList.size()]), new UploadBatchListener() {

            @Override
            public void onSuccess(List<BmobFile> files, List<String> urls) {
                //1、files-上传完成后的BmobFile集合，是为了方便大家对其上传后的数据进行操作，例如你可以将该文件保存到表中
                //2、urls-上传文件的完整url地址
                if (urls.size() == imgPathList.size()) {//如果数量相等，则代表文件全部上传完成
                    thingBean.setThingImgs(urls);
                    saveToNet(thingBean);
                }
            }

            @Override
            public void onError(int statuscode, String errormsg) {
                Toast.makeText(ReleaseActivity.this, "错误码" + statuscode + ",错误描述：" + errormsg, Toast.LENGTH_SHORT).show();
                if (mSVProgressHUD.isShowing()) {
                    mSVProgressHUD.dismiss();
                }
                btn_release_commit.setEnabled(true);

            }

            @Override
            public void onProgress(int curIndex, int curPercent, int total, int totalPercent) {
                //1、curIndex--表示当前第几个文件正在上传
                //2、curPercent--表示当前上传文件的进度值（百分比）
                //3、total--表示总的上传文件数
                //4、totalPercent--表示总的上传进度（百分比）
            }
        });
    }


    public void choseType() {
        //选项选择器
        pvOptions = new OptionsPickerView(this);

        String[] type = {"百货副食","电脑办公","化妆个护","计生保健","旅行交友","生活娱乐","手机数码","图书教材","文房乐器","箱包服饰","校园代步","运动健身"};
        //选项1

        options1Items = new ArrayList(Arrays.asList(type));

        //三级联动效果
        pvOptions.setPicker(options1Items);
        //设置选择的三级单位
//        pwOptions.setLabels("省", "市", "区");
        pvOptions.setTitle("选择分类");
        pvOptions.setCyclic(false, true, true);
        //设置默认选中的三级项目
        //监听确定选择按钮
        pvOptions.setSelectOptions(1, 1, 1);
        pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {

            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1);
                tvOptions.setText(tx);
            }
        });
        //点击弹出选项选择器
        tvOptions.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                pvOptions.show();
            }
        });
    }
}
